/**   
 *  Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
* @Title: ActionClassSearcher.java 
* @Package binder.support 
* @Description: TODO
* @author dailey_dai  
* @date Apr 12, 2012
* @version V1.0   
*/
package binder.support;

import java.lang.reflect.Method;

import binder.model.ActionBean;

public class ActionClassSearcher
{
	private String methodName;

	private String className;

	/**
	 * action method name; its formatter could only contain method name or
	 * contain full path for class name with method name;<br>
	 * for example: <li>1. binder.support.ActionClassSearcher.build <li>2. build
	 * 
	 * @param methodName
	 *            String action method name
	 * @return ActionClassSearcher
	 */
	public static ActionClassSearcher build(String methodName)
	{
		return new ActionClassSearcher(methodName);
	}

	ActionClassSearcher(String methodName)
	{
		setMethodName(methodName);
	}

	private void setMethodName(String methodName)
	{
		if (methodName == null)
			throw new NullPointerException("Method name can not be empty.");
		if (methodName.indexOf(".") != -1)
		{
			int index = methodName.lastIndexOf(".");
			this.methodName = methodName.substring(index + 1);
			this.className = methodName.substring(
				0, index);
		}
		else
		{
			this.methodName = methodName;
		}
	}

	/**
	 * search the action bean class which contain the specially method name
	 * 
	 * @param clazzs
	 *            Class<?>[]
	 * @return Class<?>
	 */
	public Class<?> search(Class<?>[] clazzs)
	{
		if (className != null)
		{
			try
			{
				return Class.forName(className);
			}
			catch (ClassNotFoundException e)
			{
				throw new IllegalArgumentException("Invalid method name[" + className + "."
					+ methodName + "] cause by class name[" + className + "] can not be found.");
			}
		}
		else if (clazzs != null)
		{
			for (Class<?> clazz : clazzs)
			{
				for (Method method : clazz.getDeclaredMethods())
				{
					if (methodName.endsWith(method.getName()))
					{
						return clazz;
					}
				}
			}
		}
		return ActionBean.class;
	}
}